package com.mmall.handler;

import com.mmall.Exception.ParamException;
import com.mmall.Exception.PermissionException;
import com.mmall.common.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
public class SpringExceptionResolver implements HandlerExceptionResolver {
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        String url = httpServletRequest.getRequestURL().toString();
        ModelAndView modelAndView;
        String defaultMsg = "系统异常";
        //要求项目中所有请求json数据，都使用.json结尾
        if (url.endsWith(".json")) {
            //数据传送
            if (e instanceof PermissionException || e instanceof ParamException) {
                JsonData data = JsonData.fail(e.getMessage());
                modelAndView = new ModelAndView("jsonView", data.toMap());//这里的jsonView与spring-servlet.xml对应
            }else{
                log.error("未知的json异常，url："+url,e);
                JsonData data = JsonData.fail(e.getMessage()!=null?e.getMessage():defaultMsg);
                modelAndView = new ModelAndView("jsonView",data.toMap());
            }
        } else if (url.endsWith(".page")){//项目中所有page页面，都使用.page结尾
            //页面传输
            log.error("未知的页面异常，url："+url,e);
            JsonData data = JsonData.fail(e.getMessage()!=null?e.getMessage():defaultMsg);
            modelAndView = new ModelAndView("exception",data.toMap());//exception是定义的一个错误页面，
        }else {
            log.error("未知异常，url："+url,e);
            JsonData data = JsonData.fail(e.getMessage()!=null?e.getMessage():defaultMsg);
            modelAndView = new ModelAndView("jsonView",data.toMap());
        }

        return modelAndView;
    }
}
